(function () {

    // 获取 wangEditor 构造函数和 jquery
    var E = window.wangEditor;
    var $ = window.jQuery;

    var idPrefix = 'tags_' + Math.random().toString().replace('.', '') + '_',
        globalNum = 1;

    function getUniqeId(){
        return idPrefix + (globalNum++); 
    }


    
    $('body').append('<div style="margin:20px;" id="tagWrap"><div class="JS_tableWrap"></div><div class="JS_fieldWrap"></div><div class="JS_paramWrap"></div><div class="JS_functionWrap"></div><div class="JS_styleWrap"></div><div class="JS_resultWrap"></div></div>')
    var $tableWrap    = $("#tagWrap .JS_tableWrap");
    var $fieldWrap    = $("#tagWrap .JS_fieldWrap");
    var $paramWrap    = $("#tagWrap .JS_paramWrap");
    var $functionWrap = $("#tagWrap .JS_functionWrap");
    var $styleWrap    = $("#tagWrap .JS_styleWrap");
    var $resultWrap   = $("#tagWrap .JS_resultWrap");


    var tagJSON = new Object;
    
    // 生成JSON
    function creatFormula(){
        var paramJSON = new Array;

        var params = $paramWrap.find("textarea");
        params.each(function() {
            var p = JSON.parse($(this).val())
            paramJSON.push(p);
        })

        var modelJSON = new Array;
        var models = $fieldWrap.find(".table-item");
        models.each(function(){
            var t = $(this).attr('data-modelId');
            modelJSON.push(t);
        })

        var _function = {'tag': $functionWrap.find("input").val()}
        tagJSON = {'param' : paramJSON, 'models':modelJSON, 'type': 1,  'result': _function};
    }

    // 清空
    function clearTagsWrap(){
        $tableWrap.html('');
        $fieldWrap.html('');
        $paramWrap.html('');
        $functionWrap.html('');
        $styleWrap.html('');
        $resultWrap.html('');
    }

    function getModelList(){
        $.ajax({
            type:"POST",
            dataType:"jsonp",
            jsonp:"callback",
            url: "http://192.168.0.137:8080/TrueDPS/trueDataController/getModelList.do",
            cache: false,
            async: false,
            success:function(msg){
                var length = typeof msg.data != 'undefined' ? msg.data.length : 0,
                i;
                
                // "modelId": "7593dfb5-6f64-444b-8590-fe557e4ab9a0",
                // "modelName": "南通地区gdp信息",
                // "modelSort": 0,
                // "modelStatus": 1,
                // "tableDesc": "南通地区gdp信息",
                // "tableName": "T_CMS_DATA_GDP2",

                var tables = msg.data
                var tableOption = '<option value="">请选择数据来源</option>';
                for(key in tables){
                    tableOption += '<option value='+ tables[key].modelId +' data-tableName="'+ tables[key].tableName +'">'+tables[key].modelName+'</option>';
                }
                // 生成来源表
                var $tableItem = $('<div class="list-item"><span class="item-label">选择来源表</span><div class="item-control"><select>'+ tableOption +'</select></div></div>');   
                $tableWrap.html('').append($tableItem);
                
                // $("#tagWrap").append($tableWrap).append($fieldWrap).append($paramWrap).append($functionWrap).append($styleWrap).append($resultWrap);
            
            }
        })
    }

    // 选择来源表
    var fieldIndex = 1; //取值索引
    $tableWrap.on("change", 'select', function(){
        var modelId = $(this).find(':selected').val();

        var modelJSON = new Array;
        var models = $fieldWrap.find(".table-item");
        models.each(function(){
            var t = $(this).attr('data-modelId');
            modelJSON.push(t);
        })

        if($.inArray(modelId, modelJSON) == -1){
            getFields(modelId);
        }

    })


    function getFields(modelId){
        $.ajax({
            type:"POST",
            dataType:"jsonp",
            jsonp:"callback",
            url: "http://192.168.0.137:8080/TrueDPS/trueDataController/getFieldList.do?modelId="+modelId,
            cache: false,
            async: false,
            success:function(msg){
                var fields = msg.data;
                var fieldItem = ''
                var fieldOption = '<option value="">请选择字段</option>';
                
                // "fieldName": "DiQu",
                // "fieldType": "varchar",
                // "guid": "eb94c7df-3e98-4f2d-811f-bc5823c2d9cc",
                // "modelId": "b9399f5b-f584-4331-ac5a-dc173e2d567d",
                // "modelName": "南通地区GDP总值",
                // "note": "地区",
                // "sort": 0,
                // "tableName": "T_CMS_DATA_GDP"

                var tableName = fields[0].tableName;
                var modelName = fields[0].modelName;
                var modelId = fields[0].modelId;
                for(key in fields){
                    fieldOption += '<option value='+ fields[key].fieldName +'>'+fields[key].note+'</option>';
                    fieldItem += '<span class="field-item" data-fieldname="'+ fields[key].fieldName +'">'+ fields[key].note +'</span>';
                }
                var $fieldSource = $('<div class="list-item" data-tablename="'+ tableName +'" data-modelId="'+ modelId +'"><select style="display:none">'+ fieldOption +'</select><span class="item-label">'+ modelName +'</span><div class="item-control">'+ fieldItem +'</div></div>');
                
                // var $fieldSource = $('<div class="list-item" data-tablename=""><select style="display:none">'+ fieldOption +'</select><span class="item-label"></span><div class="item-control">'+ fieldItem +'</div></div>');
                
                var $tableItem = $('<tr class="table-item" data-tablename="'+ tableName +'" data-modelId="'+ modelId +'"><td>'+ modelName +'<select style="display:none">'+ fieldOption +'</select></td><td>'+ fieldItem +'</td><td><span class="JS_btnDelTable btn btn-danger btn-xs">删除</span></td></tr>')


                if(!$fieldWrap.find("table").length){
                   
                    var $fieldTable = $('<table class="table table-bordered"><thead><tr><th>数据表</th><th>字段</th><th>操作</th></tr></thead><tbody></tbody></table>')
                    $fieldWrap.append($fieldTable);
                }
                $fieldWrap.find("table tbody").append($tableItem);
                // $fieldWrap.append($fieldSource);
            }
        })
    }

    $fieldWrap.on("click", ".JS_btnDelTable", function(){
        $(this).parents(".table-item").remove();
    })

    // 获取已选表字段options
    var fieldOption ='';
    function getTableOption(tableName){
        var fieldObj = $fieldWrap.find(".table-item");
        fieldObj.each(function() {
            var _tableName = $(this).attr('data-tableName');
            if(tableName == _tableName){
                fieldOption = $(this).find('select').html();
            }
        });
        return fieldOption;
    }


    // 添加取值字段内容
    function addCondition(tableName, fieldName, fieldNote, paramId){

        $("#paramWrap").html("");
        
        getTableOption(tableName);

        var $paramTable = $('<div style="margin:0 20px;"><table class="table table-bordered"><thead><tr><th>值</th><th>取值字段</th><th>条件字段</th></tr></thead><tbody></tbody></table></div>')
        
        $("#paramWrap").append($paramTable);
        

        // 添加条件字段
        $paramTable.on('click', '.JS_addCondition', function(){
            var $conditionItem = $('<tr class="condition-item"><td><select>'+ fieldOption +'</select><input type="text" placeholder="字段条件"></td><td><span class="JS_addCondition btn btn-default btn-xs">添加条件</span></td></tr>')
            $paramTable.find('.condition-wrap tbody tr:last').before($conditionItem);
            
            $paramTable.find('.condition-wrap tbody').each(function(index, el) {
                var addBtns = $(this).find('.JS_addCondition');
                addBtns.not(":last").html('删除条件').removeClass('JS_addCondition btn-primary').addClass('JS_delCondition btn-danger')
            });
        })

        // 删除条件字段
        $paramTable.on('click', '.JS_delCondition', function(){
            $(this).closest('tr').remove();
        })
    }


    // 获取字段条件
    var $paramConditionItem ='';
    var paramKey ='';
    function getCondition(layero){
        var _this = $(layero).find(".param-item");
        var _paramId = _this.find(".JS_paramId").text();
        var _fileNote = _this.find(".JS_fieldNote").text();
        var _tableName = _this.attr('data-tablename');
        var _valFieldName = _this.attr('data-fieldname');
        var conditionsObj = _this.find(".condition-item");
        var _condition = {};
        conditionsObj.each(function() {
            var _conFieldName = $(this).find(':selected').val();
            var _conCondition = $(this).find('input').val();
            _condition[_conFieldName] = _conCondition;
        });
        var _paramItem = {'table': _tableName, 'note': _fileNote, 'field':_valFieldName, 'condition':_condition};
        var paramItem = {};
        paramItem[_paramId] = _paramItem;

        $paramConditionItem = $('<span class="JS_btnDelParam delparam"><i class="fa fa-close"></i></span><span>'+ _paramId +'</span><textarea style="display:none">'+ JSON.stringify(paramItem) + '</textarea>');
        paramKey = _paramId;
    }


    // 点击选择取值字段
    var paramIndex = 1;
    $fieldWrap.on("click", ".field-item", function(){
        
        var tableName = $(this).parents(".table-item").attr("data-tableName");
        var fieldName = $(this).attr("data-fieldName");
        var fieldNote = $(this).text();
        var paramId = 'T'+paramIndex;

        addCondition(tableName, fieldName, fieldNote, paramId);
        getTableOption(tableName);

        // 插入取值字段
        var $paramItem = $('<tr class="param-item" data-tablename="'+ tableName +'" data-fieldname="'+ fieldName +'"><td class="JS_paramId" style="vertical-align: middle;">'+ paramId +'</td><td class="JS_fieldNote" style="vertical-align: middle;">'+ fieldNote +'</td><td style="padding:0;"><table class="condition-wrap table" style="margin-bottom:0;"><tbody><tr class="condition-item"><td><select>'+ fieldOption +'</select><input type="text" placeholder="字段条件"></td><td><span class="JS_delCondition btn btn-danger btn-xs">删除条件</span></td></tr><tr><td colspan="2"><span class="JS_addCondition btn btn-primary btn-xs">添加条件</span></td></tr></tbody></table></td></tr>')
        // 生成字段条件table
        $("#paramWrap").find('tbody').eq(0).append($paramItem);
        
        paramIndex ++ ;

        
        layer.open({
            type: 1,
            area: ['800px', '400px'],
            title: '插入值', 
            content: $("#paramWrap"), 
            btn: ['确定', '取消'],
            yes: function(indexa, layero){
                getCondition(layero);
                var $pp = $('<div class="paramval-item"></div>').append($paramConditionItem)
                $paramWrap.append($pp);

                setFunction(paramKey);
                
                
                layer.close(indexa);
            }
        });

        
    })


    function setFunction(paramKey){
        if($functionWrap.find('input').length){
            var _function = $functionWrap.find('input').val();
            $functionWrap.find('input').val(_function + paramKey);
        } else{
            $functionWrap.append('<span>计算公式：</span><input type="text" placeholder="计算公式" />')
                    .find('input').val(paramKey);
            $resultWrap.append('结果预览：<span class="JS_tagValue"></span>');
        }
    }


    $paramWrap.on("click", ".JS_btnDelParam", function(){
        $(this).parent(".paramval-item").remove();
        return false;
    })

    $paramWrap.on({
        mouseenter: function () {
            $(this).find(".JS_btnDelParam").show();
            layer.tips('默认就是向右的', '#id或者.class');
        },
        mouseleave: function () {
            $(this).find(".JS_btnDelParam").hide();
        }
    }, ".paramval-item"); 


    // 点击修改取值字段条件
    $paramWrap.on("click", ".paramval-item", function(){
        var paramvalItem = $(this);
        var param = JSON.parse(paramvalItem.find("textarea").val());
        var paramId = paramvalItem.find("span").text();
        var tableName = param[paramId].table;
        var fieldName = param[paramId].field;
        var fieldNote = param[paramId].note;
        var conditions = param[paramId].condition;

        getTableOption(tableName);

        addCondition(tableName, fieldName, fieldNote, paramId);

        var $paramItem = $('<tr class="param-item" data-tablename="'+ tableName +'" data-fieldname="'+ fieldName +'"><td class="JS_paramId" style="vertical-align: middle;">'+ paramId +'</td><td class="JS_fieldNote" style="vertical-align: middle;">'+ fieldNote +'</td><td style="padding:0;"><table class="condition-wrap table" style="margin-bottom:0;"><tbody></tbody></table></td></tr>')
        $("#paramWrap").find('tbody').eq(0).append($paramItem);
        
        for(i in conditions){
            var $conditionItem = $('<tr class="condition-item"><td><select>'+ fieldOption +'</select><input type="text" placeholder="字段条件" value="'+ conditions[i] +'"></td><td><span class="JS_delCondition btn btn-danger btn-xs">删除条件</span></td></tr>')
            $conditionItem.find('select').val(i)
            $paramItem.find('.condition-wrap tbody').append($conditionItem);

        }

        $paramItem.find('.condition-wrap tbody').append('<tr><td colspan="2"><span class="JS_addCondition btn btn-primary btn-xs">添加条件</span></td></tr>')

        layer.open({
            type: 1,
            area: ['800px', '400px'],
            title: '插入标签', 
            content: $("#paramWrap"), 
            btn: ['确定', '取消'],
            yes: function(indexm, layero){
                getCondition(layero)
                paramvalItem.html($paramConditionItem)
                layer.close(indexm);
            }
        });

    })

    // tag 标签
    E.createMenu(function (check) {
    
        var menuId = 'tags';
        if (!check(menuId)) {
            return;
        }
        var editor = this;
        
        // 创建 menu 对象
        var menu = new E.Menu({
            editor: editor,
            id: menuId,
            title: '标签',

            // 正常状态和选中装下的dom对象，样式需要自定义
            $domNormal: $('<a href="#" tabindex="-1"><i class="wangeditor-custom-icon-tags"></i></a>'),
            $domSelected: $('<a href="#" tabindex="-1" class="selected"><i class="wangeditor-custom-icon-tags"></i></a>')
        });


        // 创建 panel 内容


        


        // 点击菜单
        menu.clickEvent = function (e) {
            // 清空弹框内容
            clearTagsWrap();
            // 获取表数据
            getModelList();

            

            layer.open({
                type: 1,
                area: ['800px', '400px'],
                title: '插入标签', 
                content: $('#tagWrap'), 
                btn: ['测试', '确定', '取消'],
                yes: function(index){
                    // layer.close(index);
                    creatFormula();
                    var a = JSON.stringify(tagJSON);
                    $.ajax({
                        type:"POST",
                        data:a,
                        dataType:"jsonp",
                        jsonp:"callback",
                        url:"http://192.168.0.137:8080/TrueDPS/formulaController/getResult.do?function="+a,
                        success:function(msg){
                            var val;
                            if(msg.success){
                                val = msg.data[0].tag;
                            }else{
                                val = msg.error;
                            }
                            $resultWrap.find(".JS_tagValue").text(val);           
                        }
                    });
                },
                btn2: function(index){
                    creatFormula();
                    var tagId = getUniqeId();
                    var a = JSON.stringify(tagJSON);
                    var tagTem =  '<textarea style="display:none" id="'+tagId+'">'+a+'</textarea>'
                    var tagValue = $resultWrap.find(".JS_tagValue").text();
                    $("#tagTem").append(tagTem);
                    var s = '<i class="tags" data-id="'+ tagId +'">'+ tagValue +'</i>';
                    layer.close(index);
                    // 执行命令
                    editor.command(e, 'insertHtml', s);
                    clearTagsWrap();             
                },
                btn3: function(index){
                    layer.close(index);
                }
            });
        }

        

        // 增加到editor对象中
        editor.menus[menuId] = menu;
    });

    // tag toolbar
    E.plugin(function () {
        var editor = this;
        var txt = editor.txt;
        var $txt = txt.$txt;
        // 说明：设置了 max-height 之后，$txt.parent() 负责滚动处理
        var $currentTxt = editor.useMaxHeight ? $txt.parent() : $txt;
        var $currentTag;

        // 用到的dom节点
        var isRendered = false;
        var $toolbar = $('<div class="txt-toolbar"></div>');
        var $triangle = $('<div class="tip-triangle"></div>');
        var $delete = $('<a href="#"><i class="wangeditor-menu-img-trash-o"></i></a>');
        var $edit = $('<a href="#"><i class="wangeditor-custom-icon-edit"></i></a>');
        //id前缀
        

        // 渲染到页面
        function render() {
            if (isRendered) {
                return;
            }
            
            // 绑定事件
            bindEvent();

            // 拼接 渲染到页面上
            $toolbar.append($triangle)
                    .append($delete)
                    .append($edit);
            editor.$editorContainer.append($toolbar);
            isRendered = true;
        }

        // 绑定事件
        function bindEvent() {
            // 统一执行命令的方法
            var commandFn;
            function command(e, callback) {
                if (commandFn) {
                    editor.customCommand(e, commandFn, callback);
                }
            }

            // 删除
            $delete.click(function (e) {
                commandFn = function () {
                    $currentTag.remove();
                };
                command(e, function () {
                    setTimeout(hide, 100);
                });
            });

            $edit.click(function(e) {
                

                var ct = $currentTag;


                var tag = JSON.parse($("#"+$currentTag.attr('data-id')).val());
                
                clearTagsWrap()

                // 获取表数据
                getModelList();

                for(key in tag.models ){ 
                    console.log(tag.models[key]);
                    var modelId = tag.models[key];
                    getFields(modelId);
                }


                $.each(tag.param, function(key, value){
                    var paramKey = Object.keys(value)[0];
                    // console.log(value);

                    $paramConditionItem = $('<div class="paramval-item"><span class="JS_btnDelParam delparam"><i class="fa fa-close"></i></span><span>'+ paramKey +'</span><textarea style="display:none">'+ JSON.stringify(value) + '</textarea></div>');
                    $paramWrap.append($paramConditionItem);

                    
   
                });

                var paramKey = tag.result.tag;
                setFunction(paramKey);

                layer.open({
                    type: 1,
                    area: ['800px', '400px'],
                    title: '插入标签', 
                    content: $('#tagWrap'), 
                    btn: ['测试', '确定', '取消'],
                    yes: function(index){
                        creatFormula();
                        var a = JSON.stringify(tagJSON);
                        $.ajax({
                            type:"POST",
                            data:a,
                            dataType:"jsonp",
                            jsonp:"callback",
                            url:"http://192.168.0.137:8080/TrueDPS/formulaController/getResult.do?function="+a,
                            success:function(msg){
                                var val;
                                if(msg.success){
                                    val = msg.data[0].tag;
                                }else{
                                    val = msg.error;
                                }
                                $resultWrap.find(".JS_tagValue").text(val);           
                            }
                        });
                    },
                    btn2: function(index){
                        creatFormula();
                        var tagId = getUniqeId();
                        var a = JSON.stringify(tagJSON);
                        var tagTem =  '<textarea style="display:none" id="'+tagId+'">'+a+'</textarea>'
                        var tagValue = $resultWrap.find(".JS_tagValue").text();
                        $("#tagTem").append(tagTem);
                        var s = '<i class="tags" data-id="'+ tagId +'">'+ tagValue +'</i>';
                        layer.close(index);
                        // 执行命令
                        // $currentTag.remove();
                        ct.remove();

                        editor.command(e, 'insertHtml', s);         
                    },
                    btn3: function(index){
                        layer.close(index);
                    }
                })

            });

            
        }

        // 显示 toolbar
        function show() {
            if (editor._disabled) {
                // 编辑器已经被禁用，则不让显示
                return;
            }
            if ($currentTag == null) {
                return;
            }
            $currentTag.addClass('clicked');
            var tagPosition = $currentTag.position();
            var tagTop = tagPosition.top;
            var tagLeft = tagPosition.left;
            var tagHeight = $currentTag.outerHeight();
            var tagWidth = $currentTag.outerWidth();

            // --- 定位 toolbar ---

            // 计算初步结果
            var top = tagTop + tagHeight;
            var left = tagLeft;
            var marginLeft = 0;

            var txtTop = $currentTxt.position().top;
            var txtHeight = $currentTxt.outerHeight();
            if (top > (txtTop + txtHeight)) {
                // top 不得超出编辑范围
                top = txtTop + txtHeight;
            }

            // 显示（方便计算 margin）
            $toolbar.show();

            // 计算 margin
            var width = $toolbar.outerWidth();
            marginLeft = tagWidth / 2 - width / 2;

            // 定位
            $toolbar.css({
                top: top + 5,
                left: left,
                'margin-left': marginLeft
            });
            // 如果定位太靠左了
            if (marginLeft < 0) {
                // 得到三角形的margin-left
                $toolbar.css('margin-left', '0');
                $triangle.hide();
            } else {
                $triangle.show();
            }
        }
        
        // 隐藏 toolbar
        function hide() {
            if ($currentTag == null) {
                return;
            }
            $currentTag.removeClass('clicked');
            $currentTag = null;
            $toolbar.hide();
        }

        // click tag 事件
        $currentTxt.on('click', '.tags', function (e) {
            var $tag = $(e.currentTarget);

            // 渲染
            render();

            if ($currentTag && ($currentTag.get(0) === $tag.get(0))) {
                setTimeout(hide, 100);
                return;
            }

            // 显示 toolbar
            $currentTag = $tag;
            show();

            // 阻止冒泡
            e.preventDefault();
            e.stopPropagation();
            
        }).on('click keydown scroll', function (e) {
            setTimeout(hide, 100);
        });
        E.$body.on('click keydown scroll', function (e) {
            setTimeout(hide, 100);
        });
    });

   

})();